/**
 * 分支管理服务
 * 处理项目分支相关的业务逻辑
 */

// 使用统一配置入口导入所需模块
const { cloudHelper } = require('../config/project_helpers_config');
const { dateHelper } = require('../config/project_helpers_config');
const { dayjs } = require('../config/libs_config');
const statusHelper = require('../helpers/status_helper.js');

/**
 * 分支服务类
 * 处理分支管理的核心功能
 */
const branchService = {
  /**
   * 获取项目所有分支
   * @param {String} projectId 项目ID
   * @returns {Promise<Array>} 分支列表
   */
  getBranchList: async function(projectId) {
    try {
      if (!projectId) {
        throw new Error('项目ID不能为空');
      }
      
      // 构造API调用参数
      const params = {
        projectId
      };
      
      // 调用云函数获取分支列表
      const result = await cloudHelper.callCloudData('plm/branch_list', params);
      
      // 格式化分支数据
      if (result && result.list && Array.isArray(result.list)) {
        return result.list.map(branch => this._formatBranch(branch));
      }
      
      // 如果没有获取到分支数据，返回默认主分支
      return [{
        _id: '',
        name: '主分支',
        type: 'main',
        isMain: true,
        active: true,
        origin: '',
        creatorName: '系统',
        createTime: Date.now(),
        lastUpdateTime: Date.now()
      }];
      
    } catch (error) {
      console.error('[分支服务] 获取分支列表失败:', error);
      // 返回默认数据
      return [{
        _id: '',
        name: '主分支',
        type: 'main',
        isMain: true,
        active: true,
        origin: '',
        creatorName: '系统',
        createTime: Date.now(),
        lastUpdateTime: Date.now()
      }];
    }
  },
  
  /**
   * 获取分支详情
   * @param {String} branchId 分支ID
   * @returns {Promise<Object>} 分支详情
   */
  getBranchDetail: async function(branchId) {
    try {
      if (!branchId) {
        throw new Error('分支ID不能为空');
      }
      
      // 构造API调用参数
      const params = {
        branchId
      };
      
      // 调用云函数获取分支详情
      const result = await cloudHelper.callCloudData('plm/branch_detail', params);
      
      // 格式化分支数据
      if (result && result.data) {
        return this._formatBranch(result.data);
      }
      
      throw new Error('未找到分支数据');
    } catch (error) {
      console.error('[分支服务] 获取分支详情出错:', error);
      throw error;
    }
  },
  
  /**
   * 创建项目分支
   * @param {String} projectId 项目ID
   * @param {Object} branchData 分支数据
   * @returns {Promise<Object>} 创建结果
   */
  createBranch: async function(projectId, branchData) {
    try {
      if (!projectId) {
        throw new Error('项目ID不能为空');
      }
      
      if (!branchData.name) {
        throw new Error('分支名称不能为空');
      }
      
      // 构造API调用参数
      const params = {
        projectId,
        name: branchData.name,
        description: branchData.description || '',
        fromBranchId: branchData.fromBranchId || '', // 从哪个分支创建的
        type: branchData.type || 'feature', // 分支类型：feature, bugfix, release
        isMaster: branchData.isMaster || false, // 是否为主分支
        // 添加规范要求的状态字段
        status: {
          level1: branchData.level1 || 1,
          level2: branchData.level2 || 'director',
          level3: branchData.level3 || null,
          level4: branchData.level4 || null
        }
      };
      
      // 调用云函数创建分支
      const result = await cloudHelper.callCloudData('plm/create_branch', params);
      
      return result;
    } catch (error) {
      console.error('[分支服务] 创建项目分支出错:', error);
      throw error;
    }
  },
  
  /**
   * 合并分支
   * @param {String} projectId 项目ID
   * @param {String} sourceBranchId 源分支ID
   * @param {String} targetBranchId 目标分支ID
   * @returns {Promise<Object>} 合并结果
   */
  mergeBranch: async function(projectId, sourceBranchId, targetBranchId) {
    try {
      if (!projectId) {
        throw new Error('项目ID不能为空');
      }
      
      if (!sourceBranchId || !targetBranchId) {
        throw new Error('源分支ID和目标分支ID不能为空');
      }
      
      // 构造API调用参数
      const params = {
        projectId,
        sourceBranchId,
        targetBranchId
      };
      
      // 调用云函数合并分支
      const result = await cloudHelper.callCloudData('plm/branch_merge', params);
      
      return result;
    } catch (error) {
      console.error('[分支服务] 合并分支失败:', error);
      throw error;
    }
  },
  
  /**
   * 删除分支
   * @param {String} projectId 项目ID
   * @param {String} branchId 分支ID
   * @returns {Promise<Object>} 删除结果
   */
  deleteBranch: async function(projectId, branchId) {
    try {
      if (!projectId) {
        throw new Error('项目ID不能为空');
      }
      
      if (!branchId) {
        throw new Error('分支ID不能为空');
      }
      
      // 构造API调用参数
      const params = {
        projectId,
        branchId
      };
      
      // 调用云函数删除分支
      const result = await cloudHelper.callCloudData('plm/branch_delete', params);
      
      return result;
    } catch (error) {
      console.error('[分支服务] 删除分支失败:', error);
      throw error;
    }
  },
  
  /**
   * 更新分支信息
   * @param {String} branchId 分支ID
   * @param {Object} updateData 更新数据
   * @returns {Promise<Object>} 更新结果
   */
  updateBranch: async function(branchId, updateData) {
    try {
      if (!branchId) {
        throw new Error('分支ID不能为空');
      }
      
      // 构造API调用参数
      const params = {
        branchId,
        ...updateData
      };
      
      // 调用云函数更新分支
      const result = await cloudHelper.callCloudData('plm/update_branch', params);
      
      return result;
    } catch (error) {
      console.error('[分支服务] 更新分支信息出错:', error);
      throw error;
    }
  },
  
  /**
   * 构建分支树
   * @param {Array} branches 分支列表
   * @returns {Object} 树形结构的分支数据
   */
  buildBranchTree: function(branches) {
    if (!branches || !Array.isArray(branches)) {
      return { nodes: [], links: [] };
    }
    
    // 构建节点和连接
    const nodes = [];
    const links = [];
    
    // 处理每个分支
    branches.forEach(branch => {
      // 添加节点
      nodes.push({
        id: branch._id || 'main',
        name: branch.name || '主分支',
        type: branch.type,
        isMain: branch.isMain,
        createTime: branch.createTime,
        lastUpdateTime: branch.lastUpdateTime
      });
      
      // 添加连接
      if (branch.origin) {
        links.push({
          source: branch.origin,
          target: branch._id,
          mergeStatus: branch.mergeStatus || 'none'
        });
      }
    });
    
    return { nodes, links };
  },
  
  /**
   * 格式化分支数据
   * @param {Object} branch 原始分支数据
   * @returns {Object} 格式化后的分支数据
   * @private
   */
  _formatBranch: function(branch) {
    if (!branch) return null;
    
    // 默认值处理
    const formattedBranch = {
      _id: branch._id || branch.BRANCH_ID || '',
      name: branch.BRANCH_NAME || '未命名分支',
      type: branch.BRANCH_TYPE || 'feature', // feature, bugfix, release
      isMain: branch.IS_MAIN === 1,
      active: branch.ACTIVE === 1,
      origin: branch.ORIGIN_BRANCH || '',
      creatorId: branch.ADD_PERSON || '',
      creatorName: branch.ADD_PERSON_NAME || '未知',
      createTime: branch.ADD_TIME ? dateHelper.timestampToDate(branch.ADD_TIME) : null,
      lastUpdateTime: branch.LAST_UPDATE_TIME ? dateHelper.timestampToDate(branch.LAST_UPDATE_TIME) : null,
      mergeStatus: branch.MERGE_STATUS || 'none', // none, pending, merged, conflict
      description: branch.BRANCH_DESC || '',
      
      // 添加规范要求的状态字段
      level1: branch.LEVEL1 || branch.level1 || 1,
      level2: branch.LEVEL2 || branch.level2 || 'director',
      level3: branch.LEVEL3 || branch.level3 || null,
      level4: branch.LEVEL4 || branch.level4 || null,
      branchId: branch._id || branch.BRANCH_ID || '',
      branchName: branch.BRANCH_NAME || '未命名分支',
      completionPercentage: branch.COMPLETION_PERCENTAGE || branch.completionPercentage || 0,
    };
    
    // 添加规范要求的计算字段
    formattedBranch.fullStatusDesc = statusHelper.getFullStatusDesc({
      level1: formattedBranch.level1,
      level2: formattedBranch.level2,
      level3: formattedBranch.level3,
      level4: formattedBranch.level4
    });
    
    // 格式化日期显示
    if (formattedBranch.createTime) {
      formattedBranch.createTimeDisplay = dayjs(formattedBranch.createTime).format('YYYY-MM-DD HH:mm');
    }
    
    if (formattedBranch.lastUpdateTime) {
      formattedBranch.lastUpdateTimeDisplay = dayjs(formattedBranch.lastUpdateTime).format('YYYY-MM-DD HH:mm');
    }
    
    return formattedBranch;
  },
  
  /**
   * 获取合并状态文本
   * @param {String} mergeStatus 合并状态
   * @returns {String} 合并状态文本
   */
  getMergeStatusText: function(mergeStatus) {
    const statusMap = {
      'none': '未合并',
      'merged': '已合并',
      'conflict': '冲突',
      'pending': '待合并'
    };
    
    return statusMap[mergeStatus] || '未知状态';
  },
  
  /**
   * 检查分支是否可以合并
   * @param {Object} sourceBranch 源分支
   * @param {Object} targetBranch 目标分支
   * @returns {Object} 检查结果 {canMerge, conflicts}
   */
  checkMergeability: async function(sourceBranchId, targetBranchId) {
    try {
      if (!sourceBranchId || !targetBranchId) {
        throw new Error('源分支ID和目标分支ID不能为空');
      }
      
      // 构造API调用参数
      const params = {
        sourceBranchId,
        targetBranchId
      };
      
      // 调用云函数检查合并可行性
      const result = await cloudHelper.callCloudData('plm/check_mergeability', params);
      
      return result.data;
    } catch (error) {
      console.error('[分支服务] 检查分支合并可行性出错:', error);
      throw error;
    }
  },
  
  /**
   * 获取分支数据映射
   * 将项目特定字段映射到通用字段
   * @param {Object} project 项目数据
   * @param {Object} branch 分支数据
   * @returns {Object} 合并后的项目数据
   */
  getBranchDataMapping: function(project, branch) {
    if (!project) return {};
    if (!branch) return project;
    
    // 创建新对象，避免修改原始数据
    const mappedData = { ...project };
    
    // 映射分支特有字段
    if (branch.fields) {
      Object.keys(branch.fields).forEach(key => {
        mappedData[key] = branch.fields[key];
      });
    }
    
    // 处理分支状态信息，使用安全的访问方式
    const branchState = branch.state || {};
    mappedData.level1 = branch.level1 || branchState.level1 || mappedData.level1 || 1;
    mappedData.level2 = branch.level2 || branchState.level2 || mappedData.level2 || 'director';
    mappedData.level3 = branch.level3 || branchState.level3 || mappedData.level3 || null;
    mappedData.level4 = branch.level4 || branchState.level4 || mappedData.level4 || null;
    
    // 添加分支信息，使用默认值确保不为空
    mappedData.branchId = branch._id || '';
    mappedData.branchName = branch.name || '未命名分支';
    
    // 计算完整状态描述，确保statusHelper存在
    if (statusHelper && typeof statusHelper.getFullStatusDesc === 'function') {
      mappedData.fullStatusDesc = statusHelper.getFullStatusDesc(mappedData);
    } else {
      // 备用实现，生成简单的状态描述
      mappedData.fullStatusDesc = `${mappedData.level1 || '未知'} > ${mappedData.level2 || '未知'}`;
    }
    
    // 计算开发状态
    mappedData.developmentStatus = this._getDevelopmentStatus(mappedData);
    
    // 添加分支信息
    mappedData.currentBranch = {
      _id: branch._id || '',
      name: branch.name || '未命名分支',
      type: branch.type || 'main',
      isMain: branch.isMain || false
    };
    
    return mappedData;
  },
  
  /**
   * 获取项目的主分支
   * @param {String} projectId 项目ID
   * @returns {Promise} 主分支数据
   */
  getProjectMasterBranch: async function(projectId) {
    try {
      if (!projectId) {
        throw new Error('项目ID不能为空');
      }
      
      const branches = await this.getBranchList(projectId);
      return branches.find(branch => branch.isMain) || branches[0];
    } catch (error) {
      console.error('[分支服务] 获取项目主分支失败:', error);
      throw error;
    }
  },
  
  /**
   * 批量获取项目主分支
   * @param {Array} projectIds 项目ID数组
   * @returns {Promise} 主分支数据数组
   */
  getMasterBranches: async function(projectIds) {
    if (!projectIds || projectIds.length === 0) {
      return [];
    }
    
    try {
      // 构造API调用参数
      const params = {
        projectIds
      };
      
      // 调用云函数批量获取主分支
      const result = await cloudHelper.callCloudData('plm/batch_master_branches', params);
      
      // 格式化分支数据
      if (result && result.list && Array.isArray(result.list)) {
        return result.list.map(branch => this._formatBranch(branch));
      }
      
      return [];
    } catch (error) {
      console.error('[分支服务] 批量获取项目主分支失败:', error);
      return [];
    }
  },
  
  /**
   * 根据项目状态获取开发状态文本
   * @param {Object} project 项目数据
   * @returns {String} 开发状态文本
   * @private
   */
  _getDevelopmentStatus: function(project) {
    if (!project) return '未知状态';
    
    const level1 = project.level1;
    
    // 根据一级状态获取开发状态
    const statusMap = {
      1: '待立项',
      2: '开发中',
      3: '测试中',
      4: '送样阶段',
      5: '量产中',
      6: '已完成',
      7: '已关闭'
    };
    
    return statusMap[level1] || '未知状态';
  }
};

// 导出分支服务
module.exports = branchService;

// 状态流转规则
const BRANCH_STATUS_TRANSITIONS = {
  DRAFT: ['PLANNING', 'ARCHIVED'],
  PLANNING: ['DEVELOPING', 'ARCHIVED'],
  DEVELOPING: ['TESTING', 'ARCHIVED'],
  TESTING: ['COMPLETED', 'DEVELOPING', 'ARCHIVED'],
  COMPLETED: ['ARCHIVED'],
  ARCHIVED: []
};

/**
 * 校验分支状态流转是否合法
 * @param {string} currentStatus
 * @param {string} targetStatus
 * @returns {boolean}
 */
function isValidStatusTransition(currentStatus, targetStatus) {
  const allowed = BRANCH_STATUS_TRANSITIONS[currentStatus] || [];
  return allowed.includes(targetStatus);
}

/**
 * 检查分支合并冲突（预留接口）
 */
async function checkMergeConflicts(sourceBranchId, targetBranchId) {
  // TODO: 实现具体冲突检测逻辑
  return [];
}

/**
 * 记录分支操作日志
 */
async function logBranchOperation(operation, branchId, operator, details) {
  if (!db || !db.collection) return;
  await db.collection('branch_operation_logs').insertOne({
    operation,
    branchId,
    operator,
    details,
    timestamp: Date.now()
  });
}

/**
 * 分支权限校验
 */
async function checkBranchPermission(branchId, userId, operation) {
  // 这里假设有getBranchDetail和getUserDetail方法
  const branch = await branchService.getBranchDetail(branchId);
  const user = await getUserDetail(userId);
  if (!hasPermission(user, branch, operation)) {
    throw new Error('无权限执行此操作');
  }
} 